<?php

class OutputBuffer {


    /**
     * Logger.
     */
    protected $log;


    // ----------------------------------------------------- Instance Variables


    /**
     * Committed flag.
     */
    protected $committed = false;


    /**
     * Associated response.
     */
    private $response;


    /**
     * Suspended flag. All output bytes will be swallowed if this is true.
     */
    private $suspended = false;


    /**
     * Do a flush on the next operation.
     */
    private $doFlush = false;


    /**
     * Flag which indicates if the output buffer is closed.
     */
    private $closed = false;


    /**
     * State of the output buffer.
     */
    private $initial = true;


    // ------------------------------------------------------------ Constructor


    public function __construct() {

        $this->log = LoggerManager::getLogger("OutputBuffer");

        if($this->log->isDebugEnabled())
            $this->log->debug("construct()");

        ob_start(); // array(&$this, 'flush')
        ob_implicit_flush(false);

    }


    // ------------------------------------------------------------- Properties


    /**
     * Is the response output closed ?
     *
     * @return closed flag value
     */
    public function isClosed() {
        return $this->closed;
    }


    /**
     * Is the response output commited ?
     *
     * @return commited flag value
     */
    public function isCommited() {
        return $this->committed;
    }


    // --------------------------------------------------------- Public Methods


    public function close() {

        if($this->log->isDebugEnabled())
            $this->log->debug(" close()");

        if ($this->closed)
            return;

        if ($this->suspended)
            return;

        ob_end_clean();

    }


    public function commit() {

        if($this->log->isDebugEnabled())
            $this->log->debug(" commit()");

        $this->committed = true;

        ob_end_flush();

    }


    public function flush() {

        if($this->log->isDebugEnabled())
            $this->log->debug(" flush()");

        return ob_flush();

    }


    public function isNew() {
        return ($this->getCharsWritten() == 0);
    }


    public function reset() {

        if($this->log->isDebugEnabled())
            $this->log->debug(" reset()");

        $this->initial = true;

        ob_clean();

    }


    // ------------------------------------------------- Chars Handling Methods


    public function getCharsWritten() {
        return ob_get_length();
    }


    public function write($c) {

        if ($this->suspended)
            return;

        echo $c;

    }

}

?>